package filters

import (
	"github.com/sentiger/go-gateway/src"
	"net/http"
	"strings"
)

type SetHeaderFilter struct{}

func init() {
	// 注册过滤器
	src.RegisterFilter("SetHeader", NewSetHeaderFilter())
}

func NewSetHeaderFilter() *SetHeaderFilter {
	return &SetHeaderFilter{}
}

func (filter *SetHeaderFilter) Apply(config interface{}) src.GatewayFilter {

	return func(exchange *src.ServerWebExchange) src.ResponseFilter {
		config := src.ValueConfig(config.(string))
		headerValues := config.GetValue()
		for _, v := range headerValues {
			vSplit := strings.Split(v, ":")
			if len(vSplit) != 2 {
				continue
			}
			exchange.Request.Header.Set(vSplit[0], vSplit[1])
		}

		// 返回响应头
		return func(response *http.Response) {
			response.Header.Add("Age", "22")
		}
	}
}
func (filter *SetHeaderFilter) GetOrder() int {
	return 1
}
